import BaiduMapMarkers from './BaiduMapMarkers.js';
import { handleCommonResult } from '@gis/lib/utils/resolver.js';
import { getRandomPeopleName } from '@gis/lib/utils/index.js';

import { random, omit } from 'lodash-es';

async function getRandomMarkerData(num = 10) {
  const getRandom = (length) => {
    return Array.apply(null, { length })
      .map(() => random(0, 9))
      .join('');
  };
  const type = { 0: 'people', 1: 'device' };
  return {
    code: 200,
    data: Array.apply(null, { length: num }).map((n, i) => {
      return {
        id: i + 1,
        type: type[i % 2],
        name: getRandomPeopleName(),
        lng: '103.6' + getRandom(13),
        lat: '30.6' + getRandom(13),
      };
    }),
  };
}

function openInfoWindow(marker) {
  const { extraData } = marker;
  marker.openInfoWindow(
    new BMap.InfoWindow(`<div style="color: #c66621">测试信息窗口</div>`, {
      title: `<div style="color: #21c67e">${extraData.name}</div>`,
    })
  );
}

export const markersConfig = {
  camera: {
    getDataList: async () => {
      const list = handleCommonResult(await getRandomMarkerData(20));
      return list.map((item) => ({ ...item, title: item.name }));
    },
    typeName: '监控',
    icon: '',
    filterIcon: '',
    onClick(e) {
      // console.log(e);
      openInfoWindow(e.target);
    },
  },
};

export default {
  name: 'BaiduMapMarkerLayer',
  inheritAttrs: false,
  props: {
    /* _filter_type Array */
    value: { type: Array, default: () => ['camera'] },
  },
  created() {
    this.layer = new BaiduMapMarkers(this.$attrs.map);
    Object.keys(markersConfig).forEach((type) => {
      const config = markersConfig[type];
      config.getDataList().then((list) => {
        const opt = omit(config, ['getDataList']);
        list = list.map((item) => {
          return Object.assign({}, item, opt, { _filter_type: type });
        });
        this.layer.add(list, this.value.includes(type));
      });
    });
    this.$watch(
      () => this.value,
      function (value) {
        this.layer.toggle((item) => value.includes(item._filter_type));
      },
      { immediate: false, deep: true }
    );
  },
  unmounted() {
    this.layer.destroy();
  },
  methods: {
    getData(predicate) {
      return this.layer.getData(predicate);
    },
    getMarker(predicate) {
      return this.layer.getMarker(predicate);
    },
  },
  render() {
    return null;
  },
};
